//
// Created by zyw on 23-2-23.
//

#include <unistd.h>
#include <getopt.h>

#include "rt_print.h"
#include "cm_thread_task_manager.h"

class ThreadTOne : public CMThreadRunImpl
{
  public:
    ThreadTOne()
    {
        exit = false;
        i = 0;
    }
    virtual int run()
    {
        if (exit)
        {
            return 0;
        }
        rtdebug("one [%s] [%d]", threadItem.name.c_str(), i);

        sleep(1);
        if (i++ == 10)
        {
            exit = true;
        }
        return 0;
    }
    virtual bool runDone()
    {
        return exit;
    }
  private:
    bool exit;
    int i;
};

class ThreadAlone : public CMThreadRunImpl
{
  public:
    ThreadAlone()
    {
        exit = false;
    }
    virtual int run()
    {
        if (exit)
        {
            return 0;
        }
        int i = 0;
        while (i++ < 10)
        {
            rtdebug("one [%s] [%d]", threadItem.name.c_str(), i);
            sleep(1);
        }

        exit = true;
        return 0;
    }
    virtual bool runDone()
    {
        return exit;
    }
  private:
    bool exit;
};

void test_run_together()
{
    // 必須用 new 创建，内部处理时运行完成会进行销毁
    ThreadTOne *oneThread = new ThreadTOne;
    ThreadTOne *twoThread = new ThreadTOne;
    ThreadAlone *aloneThreadOne = new ThreadAlone;
    ThreadAlone *aloneThreadTwo = new ThreadAlone;

    rtdebug("start");

    CMThreadTaskManager taskManager;
    taskManager.start();

    std::string name("oneThread");
    taskManager.addToThread(oneThread, name, false);
    sleep(2);
    name = "twoThread";
    taskManager.addToThread(twoThread, name, false);
    sleep(2);

    taskManager.debug();
    name = "aloneOneThread";
    taskManager.addToThread(aloneThreadOne, name);
    sleep(2);
    name = "aloneTwoThread";
    taskManager.addToThread(aloneThreadTwo, name);

    rtdebug("done");

    int i = 0;
    while (i++ < 30)
    {
        if (i % 5 == 0)
        {
            taskManager.debug();
        }
        sleep(1);
    }

    taskManager.stop();
}

void test_thread()
{
    test_run_together();
}

int main(int argc, char **args)
{
    printf("VERSION [%s][%s]\n", __DATE__, __TIME__);
    int c = 0;
    char *conf = "./zlog_default_pc.conf";
    while ((c = getopt(argc, args, "c:")) != -1)
    {
        switch (c)
        {
        case 'c':
            conf = optarg;
            break;
        }
    }
    printf("log file [%s]\n", conf);
    int ret = rt_print_init(RT_PRINT_ALL, RT_PRINT_STYLE_ALL, 1, "thread_task");
    printf("ret=[%d]\n", ret);
    rtdebug("startup [%s][%s]", __DATE__, __TIME__);

    test_thread();

    return 0;
}
